<template>
  <div class="task-management-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form
        :inline="true"
        class="search-form"
      >
        <el-form-item label="任务ID">
          <el-input
            v-model="searchQuery.taskId"
            placeholder="请输入任务ID"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="任务类型">
          <el-select
            v-model="searchQuery.taskType"
            placeholder="请选择任务类型"
            clearable
            style="width: 200px"
          >
            <el-option
              label="全部"
              value=""
            />
            <el-option
              label="登录"
              value="登录"
            />
            <el-option
              label="发表"
              value="发表"
            />
            <el-option
              label="评论"
              value="评论"
            />
            <el-option
              label="点赞"
              value="点赞"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="batchDelete"
          >
            批量删除({{ selectedIds.length }})
          </el-button>
          <el-button
            type="success"
            @click="showAddDialog"
          >
            新增任务
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="currentPageData"
      border
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold'
      }"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <!-- 1.多选框列 -->
      <!-- 2.固定宽度 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        type="selection"
        width="80"
        align="center"
      />

      <!-- ID列 -->
      <!-- 1.绑定roleName字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        prop="id"
        label="任务ID"
        width="120"
        align="center"
      />

      <!-- 角色名称列 -->
      <!-- 1.绑定roleName字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        prop="taskType"
        label="任务类型"
        width="200"
        align="center"
      />

      <!-- 备注列 -->
      <!-- 1.绑定remark字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        prop="experience"
        label="经验值"
        align="center"
      />

      <el-table-column
        prop="points"
        label="积分"
        align="center"
      />

      <el-table-column
        prop="times"
        label="需完成次数"
        align="center"
      />

      <!-- 创建时间列 -->
      <!-- 1.绑定createTime字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <!-- 4.固定宽度 -->
      <el-table-column
        prop="publishTime"
        label="创建时间"
        align="center"
        width="280"
      />

      <!-- 操作列 -->
      <!-- 1.列标题 -->
      <!-- 2.居中对齐 -->
      <!-- 3.固定宽度 -->
      <el-table-column
        label="操作"
        align="center"
        width="280"
      >
        <!-- 自定义列模板 -->
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <!-- 1.小尺寸按钮 -->
          <!-- 2.点击事件，传入当前行数据 -->
          <el-button
            size="mini"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>

          <!-- 删除按钮 -->
          <!-- 1.小尺寸按钮 -->
          <!-- 2.红色警示按钮 -->
          <!-- 3.点击事件，传入当前行id -->
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <span>共 {{ filteredTaskList.length }} 条</span>
      <el-select
        v-model="pagination.pageSize"
        size="mini"
        style="width: 100px; margin: 0 15px"
        @change="handleSizeChange"
      >
        <el-option
          v-for="item in [10, 20, 50]"
          :key="item"
          :label="`${item}条/页`"
          :value="item"
        />
      </el-select>
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        layout="prev, pager, next, jumper"
        :total="filteredTaskList.length"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :modal="false"
    >
      <el-form
        ref="taskForm"
        :model="currentTask"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item
          label="任务类型"
          prop="taskType"
        >
          <el-select
            v-model="currentTask.taskType"
            placeholder="请选择任务类型"
          >
            <el-option
              label="登录"
              value="登录"
            />
            <el-option
              label="发表"
              value="发表"
            />
            <el-option
              label="评论"
              value="评论"
            />
            <el-option
              label="点赞"
              value="点赞"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="经验值"
          prop="experience"
        >
          <el-input-number
            v-model="currentTask.experience"
            :min="0"
            :max="1000"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          label="积分"
          prop="points"
        >
          <el-input-number
            v-model="currentTask.points"
            :min="0"
            :max="1000"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          label="完成次数"
          prop="times"
        >
          <el-input-number
            v-model="currentTask.times"
            :min="1"
            :max="100"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="confirmSubmit"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TaskManagement',
  data () {
    return {
      searchQuery: {
        taskId: '',
        taskType: ''
      },
      selectedIds: [],
      dialogVisible: false,
      dialogTitle: '新增任务',
      taskList: [
        { id: 1, taskType: '登录', experience: 10, points: 5, times: 1, publishTime: '2023-08-01 00:30:00' },
        { id: 2, taskType: '发表', experience: 20, points: 10, times: 1, publishTime: '2023-08-02 14:15:00' },
        { id: 3, taskType: '评论', experience: 15, points: 8, times: 3, publishTime: '2023-09-03 18:20:00' },
        { id: 4, taskType: '点赞', experience: 5, points: 2, times: 5, publishTime: '2023-09-04 15:45:00' },
        { id: 5, taskType: '评论', experience: 12, points: 8, times: 1, publishTime: '2023-09-04 08:30:00' },
        { id: 6, taskType: '发表', experience: 25, points: 12, times: 1, publishTime: '2023-08-08 11:26:00' },
        { id: 7, taskType: '评论', experience: 18, points: 8, times: 4, publishTime: '2023-08-07 13:40:00' },
        { id: 8, taskType: '点赞', experience: 8, points: 4, times: 8, publishTime: '2023-09-08 15:55:00' },
        { id: 9, taskType: '登录', experience: 15, points: 7, times: 1, publishTime: '2023-09-08 00:10:00' },
        { id: 10, taskType: '发表', experience: 30, points: 15, times: 1, publishTime: '2023-09-19 09:30:00' }
      ],
      filteredTaskList: [], // 存储查询结果
      isSearched: false, // 是否已执行查询
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      currentTask: {
        id: 0,
        taskType: '',
        experience: 0,
        points: 0,
        times: 1,
        publishTime: ''
      },
      formRules: {
        taskType: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        experience: [
          { required: true, message: '请输入经验值', trigger: 'blur' }
        ],
        points: [
          { required: true, message: '请输入积分', trigger: 'blur' }
        ],
        times: [
          { required: true, message: '请输入完成次数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    currentPageData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.isSearched
        ? this.filteredTaskList.slice(start, end)
        : this.taskList.slice(start, end)
    },
    totalItems () {
      return this.isSearched
        ? this.filteredTaskList.length
        : this.taskList.length
    }
  },
  methods: {
    getTagType (type) {
      const types = {
        登录: 'success',
        发表: 'warning',
        评论: 'info',
        点赞: 'danger'
      }
      return types[type] || ''
    },
    handleSearch () {
      this.isSearched = true
      this.pagination.currentPage = 1
      this.filteredTaskList = this.taskList.filter(task => {
        const idMatch = !this.searchQuery.taskId ||
          task.id.toString().includes(this.searchQuery.taskId)
        const typeMatch = !this.searchQuery.taskType ||
          task.taskType === this.searchQuery.taskType
        return idMatch && typeMatch
      })
    },
    resetSearch () {
      this.isSearched = false
      this.searchQuery = {
        taskId: '',
        taskType: ''
      }
      this.pagination.currentPage = 1
      this.filteredTaskList = []
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
    },
    handleSelectionChange (selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    showAddDialog () {
      this.dialogTitle = '新增任务'
      this.currentTask = {
        id: 0,
        taskType: '',
        experience: 0,
        points: 0,
        times: 1,
        publishTime: new Date().toLocaleString()
      }
      this.dialogVisible = true
    },
    handleEdit (row) {
      this.dialogTitle = '编辑任务'
      this.currentTask = { ...row }
      this.dialogVisible = true
    },
    confirmSubmit () {
      this.$refs.taskForm.validate(valid => {
        if (valid) {
          if (this.currentTask.id) {
            // 编辑任务
            const index = this.taskList.findIndex(task => task.id === this.currentTask.id)
            if (index !== -1) {
              this.taskList.splice(index, 1, { ...this.currentTask })
            }
          } else {
            // 新增任务
            const newId = this.taskList.length > 0
              ? Math.max(...this.taskList.map(task => task.id)) + 1
              : 1

            // 计算新数据应该插入的页码
            const totalItems = this.isSearched
              ? this.filteredTaskList.length
              : this.taskList.length
            const totalPages = Math.ceil((totalItems + 1) / this.pagination.pageSize)

            // 添加新任务
            this.taskList.push({
              ...this.currentTask,
              id: newId,
              publishTime: new Date().toLocaleString()
            })

            // 如果是查询状态，更新过滤后的列表
            if (this.isSearched) {
              this.handleSearch()
            }

            // 自动跳转到包含新数据的页面
            this.pagination.currentPage = totalPages
          }

          this.$message.success('保存成功')
          this.dialogVisible = false
        }
      })
    },
    batchDelete () {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('确定删除选中的任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.taskList = this.taskList.filter(task => !this.selectedIds.includes(task.id))
        this.selectedIds = []
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleDelete (id) {
      this.$confirm('确定删除该任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.taskList = this.taskList.filter(task => task.id !== id)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.task-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
}

.el-table {
  width: 100%;
}

.el-table::before {
  height: 0;
}

.el-table--border::after,
.el-table--group::after {
  width: 0;
}

.el-table td,
.el-table th {
  padding: 12px 0;
  white-space: nowrap;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.pagination-area .el-pagination {
  margin-left: 15px;
}

.el-tag {
  font-size: 12px;
  padding: 0 10px;
  height: 28px;
  line-height: 26px;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .search-form .el-form-item .el-input,
  .search-form .el-form-item .el-select {
    width: 100% !important;
  }

  .pagination-area {
    flex-direction: column;
    align-items: flex-start;
  }
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #f5f7fa !important;
}
</style>
